#include "cgal_source_poly.h"
#include <vector>
#include <vtkCell.h>
#include <vtkCellArray.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkNew.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkType.h>

namespace cgalView {
int cgal_source_poly::RequestData(vtkInformation *request,
                                  vtkInformationVector **inInfoVector,
                                  vtkInformationVector *outInfoVector) {
  if (!d_mesh) {
    return 0;
  }

  if (d_mesh->is_empty()) {
    return 0;
  }

  auto output = vtkPolyData::GetData(outInfoVector);
  if (!output) {
    return -1;
  }

  vtkNew<vtkPoints> points{};
  for (auto const &p : d_mesh->points()) {
    points->InsertNextPoint(p.x(), p.y(), p.z());
  }

  vtkNew<vtkCellArray> cells{};
  for (auto f : d_mesh->faces()) {
    std::vector<vtkIdType> cell{};
    for (auto v : d_mesh->vertices_around_face(d_mesh->halfedge(f))) {
      cell.push_back(v.id());
    }
    cells->InsertNextCell(cell.size(), cell.data());
  }

  output->SetPoints(points);
  output->SetPolys(cells);

  return 0;
}
} // namespace cgalView